//
//  JDStickyHeaderCollectionViewLayout.swift
//  DragonWallet
//
//  Created by volantPig on 2025/9/27.
//

import UIKit

//class XLPlainFlowLayout: UICollectionViewFlowLayout {
//    
//    var naviHeight: CGFloat = UIDevice().safeAreaInset.top
//    
//    override init() {
//        super.init()
//    }
//    
//    required init?(coder: NSCoder) {
//        super.init(coder: coder)
//    }
//    
//    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
//        // 获取父类返回的数组并转换为可变数组
//        guard let superArray = super.layoutAttributesForElements(in: rect) else { return nil }
//        let mutableArray = NSMutableArray(array: superArray)
//        
//        // 创建存储索引的集合
//        var noneHeaderSections = IndexSet()
//        
//        // 遍历所有元素，收集包含cell的分区
//        for attributes in superArray {
//            if attributes.representedElementCategory == .cell {
//                noneHeaderSections.insert(attributes.indexPath.section)
//            }
//        }
//        
//        // 移除已有header的分区
//        for attributes in superArray {
//            if attributes.representedElementKind == UICollectionView.elementKindSectionHeader {
//                noneHeaderSections.remove(attributes.indexPath.section)
//            }
//        }
//        
//        // 为没有header的分区添加header属性
//        noneHeaderSections.forEach { section in
//            let indexPath = IndexPath(item: 0, section: section)
//            if let attributes = self.layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: indexPath) {
//                mutableArray.add(attributes)
//            }
//        }
//        
//        // 处理header的悬停效果
//        for attributes in mutableArray {
//            guard let attributes = attributes as? UICollectionViewLayoutAttributes,
//                  attributes.representedElementKind == UICollectionView.elementKindSectionHeader else {
//                continue
//            }
//            
//            let section = attributes.indexPath.section
//            let numberOfItemsInSection = self.collectionView?.numberOfItems(inSection: section) ?? 0
//            
//            let firstItemIndexPath = IndexPath(item: 0, section: section)
//            let lastItemIndexPath = IndexPath(item: max(0, numberOfItemsInSection - 1), section: section)
//            
//            let firstItemAttributes: UICollectionViewLayoutAttributes
//            let lastItemAttributes: UICollectionViewLayoutAttributes
//            
//            if numberOfItemsInSection > 0 {
//                firstItemAttributes = self.layoutAttributesForItem(at: firstItemIndexPath) ?? UICollectionViewLayoutAttributes()
//                lastItemAttributes = self.layoutAttributesForItem(at: lastItemIndexPath) ?? UICollectionViewLayoutAttributes()
//            } else {
//                firstItemAttributes = UICollectionViewLayoutAttributes()
//                let y = attributes.frame.maxY + self.sectionInset.top
//                firstItemAttributes.frame = CGRect(x: 0, y: y, width: 0, height: 0)
//                lastItemAttributes = firstItemAttributes
//            }
//            
//            var rect = attributes.frame
//            let offset = (self.collectionView?.contentOffset.y ?? 0) + naviHeight
//            let headerY = firstItemAttributes.frame.origin.y - rect.height - self.sectionInset.top
//            let maxY = max(offset, headerY)
//            let headerMissingY = lastItemAttributes.frame.maxY + self.sectionInset.bottom - rect.height
//            rect.origin.y = min(maxY, headerMissingY)
//            attributes.frame = rect
//            attributes.zIndex = 7
//        }
//        
//        return mutableArray.copy() as? [UICollectionViewLayoutAttributes]
//    }
//    
//    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
//        return true
//    }
//}

// --- 分割线 ---  上面的是好用的，下面的是在测试中的

class XLPlainFlowLayout: UICollectionViewFlowLayout {
    
    var naviHeight: CGFloat = 64.0
    var onStickyStateChange: ((Int, Bool) -> Void)?
    private var stickyStates: [Int: Bool] = [:]
    
    override init() {
        super.init()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        // 获取父类返回的数组并转换为可变数组
        guard let superArray = super.layoutAttributesForElements(in: rect) else { return nil }
        let mutableArray = NSMutableArray(array: superArray)
        
        // 创建存储索引的集合
        var noneHeaderSections = IndexSet()
        
        // 遍历所有元素，收集包含cell的分区
        for attributes in superArray {
            if attributes.representedElementCategory == .cell {
                noneHeaderSections.insert(attributes.indexPath.section)
            }
        }
        
        // 移除已有header的分区
        for attributes in superArray {
            if attributes.representedElementKind == UICollectionView.elementKindSectionHeader {
                noneHeaderSections.remove(attributes.indexPath.section)
            }
        }
        
        // 为没有header的分区添加header属性
        noneHeaderSections.forEach { section in
            let indexPath = IndexPath(item: 0, section: section)
            if let attributes = self.layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: indexPath) {
                mutableArray.add(attributes)
            }
        }
        
        // 处理header的悬停效果
        for case let attributes as UICollectionViewLayoutAttributes in mutableArray {
            guard attributes.representedElementKind == UICollectionView.elementKindSectionHeader else {
                continue
            }
            
            let section = attributes.indexPath.section
            let numberOfItemsInSection = self.collectionView?.numberOfItems(inSection: section) ?? 0
            
            let firstItemIndexPath = IndexPath(item: 0, section: section)
            let lastItemIndexPath = IndexPath(item: max(0, numberOfItemsInSection - 1), section: section)
            
            let firstItemAttributes: UICollectionViewLayoutAttributes
            let lastItemAttributes: UICollectionViewLayoutAttributes
            
            if numberOfItemsInSection > 0 {
                firstItemAttributes = self.layoutAttributesForItem(at: firstItemIndexPath) ?? UICollectionViewLayoutAttributes()
                lastItemAttributes = self.layoutAttributesForItem(at: lastItemIndexPath) ?? UICollectionViewLayoutAttributes()
            } else {
                firstItemAttributes = UICollectionViewLayoutAttributes()
                let y = attributes.frame.maxY + self.sectionInset.top
                firstItemAttributes.frame = CGRect(x: 0, y: y, width: 0, height: 0)
                lastItemAttributes = firstItemAttributes
            }
            
            // 获取当前header的frame
            var rect = attributes.frame
            
            // 当前的滑动距离 + 因为导航栏产生的偏移量
            let offset = (self.collectionView?.contentOffset.y ?? 0) + naviHeight
            
            // 第一个cell的y值 - 当前header的高度 - 可能存在的sectionInset的top
            let headerY = firstItemAttributes.frame.origin.y - rect.size.height - self.sectionInset.top
            
            // 检测悬停状态变化
            let isSticky = offset > headerY
            let previousStickyState = stickyStates[section] ?? false
            
            if isSticky != previousStickyState {
                stickyStates[section] = isSticky
                DispatchQueue.main.async {
                    self.onStickyStateChange?(section, isSticky)
                }
                
                print("Section \(section) 悬停状态变化: \(isSticky ? "开始悬停" : "结束悬停")")
                print("Offset: \(offset), HeaderY: \(headerY), isSticky: \(isSticky)")
            }
            
            // 哪个大取哪个，保证header悬停
            let maxY = max(offset, headerY)
            
            // 最后一个cell的y值 + 最后一个cell的高度 + 可能存在的sectionInset的bottom - 当前header的高度
            let headerMissingY = lastItemAttributes.frame.maxY + self.sectionInset.bottom - rect.size.height
            
            // 给rect的y赋新值，因为在最后消失的临界点要跟谁消失，所以取小
            rect.origin.y = min(maxY, headerMissingY)
            
            // 给header的结构信息的frame重新赋值
            attributes.frame = rect
            
            // 设置zIndex确保header在cell上面
            attributes.zIndex = 7
        }
        
        return mutableArray.copy() as? [UICollectionViewLayoutAttributes]
    }
    
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
    
    // 清理状态的方法（可选）
    func clearStickyStates() {
        stickyStates.removeAll()
    }
    
    // 获取当前悬停状态的方法
    func isSectionSticky(_ section: Int) -> Bool {
        return stickyStates[section] ?? false
    }
}
